package com.jweb.framework.http.json;

import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

import com.alibaba.fastjson.JSON;
import com.jweb.framework.core.CoreRuntimeException;
import com.jweb.framework.core.channel.Transform;

/**
 * 修改人： Thomas
 * 修改内容：新增 
 * 类说明：报文解析
 */
public class JsonDecoder implements Transform {
	
	private String encoding = "UTF8" ;
	
	public void setEncoding(String s){
		if("UTF-8".equals(s)){
			s = "UTF8";
		}
		else if("UTF-16BE".equals(s)){
			s = "UTF16_BE";
		}
		else if("UTF-16LE".equals(s)){
			s = "UTF16_LE";
		}
		else if("UTF-32BE".equals(s)){
			s = "UTF32_BE";
		}
		else if("UTF-32LE".equals(s)){
			s = "UTF32_LE";
		}
		else {
			throw new IllegalArgumentException("unsupported encoding , support:UTF-8 , UTF-16BE , UTF-16LE , UTF-32BE , UTF-32LE . ");
		}
		this.encoding = s ;
	}
	
	public boolean support(Object obj) {
		
		return obj!=null && ((obj instanceof byte[]) || (obj instanceof String) || (obj instanceof InputStream));
	}
	
	public Object transform(Object obj , String s) throws CoreRuntimeException {

		String str = null ;
		if(obj instanceof byte[]){
			try {
				str = (this.encoding == null) ? new String((byte[])obj) : new String((byte[])obj , this.encoding) ;
			} catch (Exception e) {
				throw new CoreRuntimeException("JAVAHT0031", "unsupport_encoding", e);
			}
		}
		else {
			str = (String) obj ;
		}
		
		if((str!=null) && (str.trim().equals(""))){
			return new HashMap();
		}
		
		return JSON.parseObject(str , Map.class);
	}
}
